package fun.ticsmyc.multiThread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Ticsmyc
 * @date 2020-07-08 15:17
 */
public class 死锁 {
    private static ReentrantLock lock1 = new ReentrantLock();
    private static ReentrantLock lock2 = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(()->{
            System.out.println(Thread.currentThread().getName() +"尝试锁1");
            lock1.lock();
            System.out.println(Thread.currentThread().getName() +"锁1成功");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() +"尝试锁2");
            boolean flag =false;
            try {
                flag = lock2.tryLock(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() +"锁2："+flag);
        }).start();

        new Thread(()->{
            System.out.println(Thread.currentThread().getName() +"尝试锁2");
            lock2.lock();
            System.out.println(Thread.currentThread().getName() +"锁2成功");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() +"尝试锁1");
            boolean flag =false ;
            try {
                flag=lock1.tryLock(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() +"锁1："+flag);
        }).start();
    }
}
